package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil
import com.kanshu.ksgb.fastread.doudou.common.view.CustomDialog
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BonusPool
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BonusPool.NO_CONFIG
import com.kanshu.ksgb.fastread.doudou.common.business.dialog.CommonDialog
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.activity_profit.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

@Route(path = ARouterConfig.PERSONAL_PROFIT)
class ProfitActivity : BaseActivity() {
    val subject = PublishSubject.create<Int>()
    val ACTION_DESTROY = 8

    var bonusPool: BonusPool? = null
    var timeUnlock = false
    var phone = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_profit)
        title = "分红池"
        phone = StorageUtils.getPreference(this@ProfitActivity, Constants.SP_NAME, Constants.USER_BIND_PHONE + UserUtils.getUserId(), "")
        btn_open.setImageResource(R.mipmap.open_unlock)
        btn_open.setOnClickListener {
            if(TextUtils.isEmpty(phone)){
                CommonDialog.show(activity, "您的账号还未绑定手机号，处于高危状态。为保障账号安全，需绑定手机号，才能兑换金豆！", object : CustomDialog.Callback {
                    override fun onSure(dialog: Dialog) {
                        var map = HashMap<String,Integer>()
                        map["type"] = Integer(BindPhoneActivity.BIND_PHONE)
                        ARouterUtils.toActivity(ARouterConfig.PERSONAL_BIND_PHONE, map)
                        dialog.dismiss()
                    }

                    override fun onCancel(dialog: Dialog) {
                        dialog.dismiss()
                    }
                }).setSureText("立即绑定").setCancelText("残忍退出")
                return@setOnClickListener
            }
            if (timeLeft == NO_CONFIG) {
                ToastUtil.showMessage("分红池未配置")
                return@setOnClickListener
            }
            if (bonusPool == null || !timeUnlock) {
                ToastUtil.showMessage("分红池未开启")
            } else {
                val userSignInUnlock = bonusPool?.account_info?.unlock == 1
                if (userSignInUnlock) {
                    var params = HashMap<String,Parcelable?>()
                    params["data"]= bonusPool
                    ARouterUtils.toActivity(ARouterConfig.PERSONAL_BONUS_OPEN, params)
                } else
                    ToastUtil.showMessage("签到次数未满足条件")
            }
        }
        EventBus.getDefault().register(this)
        loadBonusPoolInfo()
    }

    var observable: Observable<Int>? = null
    private var timeLeft = NO_CONFIG
    private fun startCountDown() {
        if (bonusPool == null) {
            return
        }
        timeLeft = bonusPool?.wait_seconds ?: NO_CONFIG

        if (timeLeft == NO_CONFIG) {
            return
        }

        if (timeLeft == 0L) {
            unlockBonusPool()
            return
        }
        Observable.intervalRange(1, timeLeft + 1, 0, 1, TimeUnit.SECONDS)
                .takeUntil(subject)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<Long> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(t: Long?) {
                        updateCountDonwView(timeLeft - (t ?: 0))
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                    }

                })

    }

    private val str2W = "%1$02d"
    private val secondesOfDay = 86400
    private var lastTimeStr: String? = null
    private fun updateCountDonwView(secondsLeft: Long) {
        val day = secondsLeft / secondesOfDay
        val leftHour = secondsLeft % secondesOfDay / 3600
        val leftMin = secondsLeft % secondesOfDay % 3600 / 60 + 1
        val builder = StringBuilder()
        builder.append(String.format(str2W, day))
        builder.append(String.format(str2W, leftHour))
        builder.append(String.format(str2W, leftMin))
        val tmp = builder.toString()
        timeUnlock = secondsLeft <= 0L
        if (TextUtils.equals(lastTimeStr, tmp)) {
            return
        }
        lastTimeStr = tmp

        tmp.forEachIndexed { index, c ->
            val viewId = timeviews.elementAtOrNull(index)
            if (viewId != null) {
                val view = findViewById<TextView>(viewId)
                view.text = c.toString()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleBindEvent(event: BindEvent) {
        if(event.code == BindEvent.SUCCESS) {
            phone = event.data
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        subject.onNext(ACTION_DESTROY)
    }

    private fun unlockBonusPool() {
        timeUnlock = true
    }

    private fun loadBonusPoolInfo() {
        val helper = RetrofitHelper.getInstance()
        helper.createService(PersonCenterService::class.java)
                .getBonuspools()
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<BonusPool>> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(t: BaseResult<BonusPool>?) {
                        t?.result?.data?.run {
                            this@ProfitActivity.bonusPool = this
                            val rmbFen = bonusPool?.residue_amount?.toInt() ?: 0
                            val rmbYuan = formatYuan(rmbFen)
                            total.text = rmbYuan.total
                            txt2.text = rmbYuan.unit
                            startCountDown()
                        }
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                    }

                })
    }

    companion object {
        @JvmStatic
        fun actionStart(activity: Activity) {
            activity.startActivity(Intent(activity, ProfitActivity::class.java))
        }
    }

    private val timeviews = arrayListOf(R.id.day1, R.id.day2, R.id.hour1, R.id.hour2, R.id.minute1, R.id.minute2)
}

class RMBYuan {
    var unit: String = "元"
    var total: String = "0.0"
}

fun formatYuan(unitFen: Int): RMBYuan {
    val result = RMBYuan()
    var total = unitFen
    if (total > 100000000) {
        result.unit = "万元"
        total /= 10000
    }
    result.total = String.format("%1$.1f", total.toFloat() / 100)
    return result
}
